<?php

namespace Wcent\Controller;

use Think\Controller;

class CommController extends Controller
{
    public $openid;
    public $wexinfo;

    public function _initialize()
    {
        if (!$this->is_weixin()) {
            $this->display("Index/error");
            exit;
        }
        $ssid = session("wxopens");
        if ($ssid == null) {
            $tmp = $this->getbaing();
            if ($tmp) {
                session("wxopens", $tmp);
                $this->openid = $tmp["openid"];
                $this->wexinfo = $tmp;
            }
        } else {
            $this->openid = $ssid["openid"];
            $this->wexinfo = $ssid;
        }
    }

    /**
     * 判断是否是微信端
     * @return boolean
     */
    private function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    private function getbaing()
    {
        $wechat = D("Wehat");
        $para = $_GET;
        if (!$wechat->redrict($para)) {
            return false;
        }
        $tmp = $wechat->getAccessToken($para['code']);
        if (!$tmp["status"]) {
            return false;
        }
        return $wechat->getUserInfo($tmp['token'], $tmp['openid']);
    }
}
